package com.sise.rsc.service;


import com.sise.rsc.entity.Role;
import com.sise.rsc.entity.User;
import com.sise.rsc.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {

        User user = userRepository.findUserByUsername(userName);
        if (user == null)
            throw  new UsernameNotFoundException("用户名不存在！");
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Role> roles = user.getRoles();

        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getAuthority()));
        }

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),user.getPassword(),authorities);
    }

    public User findUserByUsername(String username){
        return userRepository.findUserByUsername(username);
    }
    public void save(User user){
        userRepository.save(user);
    }

}
